package it.sd.wdc.spider;

import it.sd.wdc.spider.executer.ScriptExecuter;
import it.sd.wdc.spider.repository.ScriptConfigurationException;
import it.sd.wdc.spider.repository.ScriptRepository;
import it.sd.wdc.spider.repository.WDCService;
import it.sd.wdc.spider.repository.WDCTemplate;
import it.sd.wdc.spider.repository.template.SpiderNodeTemplate;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.w3c.dom.Document;

public class WdcSpiderManager {

	private String defaultDao = null;
	private ScriptRepository repository = null;
	
	private HashMap<String, ScriptRepository> daos 
				= new HashMap<String, ScriptRepository>();

	public WdcSpiderManager(List<ScriptRepository> lista) 
				throws Exception {
		
		for (Iterator<ScriptRepository> iterator = lista.iterator(); iterator.hasNext();) {
			ScriptRepository dao = iterator.next();
			daos.put(dao.getId(), dao);
			dao.load();
			
			if (defaultDao==null) {
				defaultDao = dao.getId();
			}
		}
		
		repository = daos.get(defaultDao);
	}

	public void execute(WdcSpiderRequest ric) throws ScriptConfigurationException, Exception {
		ScriptExecuter executer = new ScriptExecuter();
		executer.setRepository(repository);
		executer.execute(ric);
	}
	
	public Document executeSinglePage(String method, String url, SpiderNodeTemplate template) throws ScriptConfigurationException, Exception {
		ScriptExecuter executer = new ScriptExecuter();
		executer.setRepository(repository);
		return executer.executeSinglePage(method, url, template);
	}
	
	public ScriptRepository getRepository() throws Exception {
		return repository;
	}

	public void store(WDCService service) throws Exception {
		store(defaultDao, service);
	}
	public void store(WDCTemplate template) throws Exception {
		store(defaultDao, template);
	}
	
	public void store(String name, WDCService service) throws Exception {
		
		if (service.isNewData()) {
			service.setId(null);
		}
		
		daos.get(name).store(service);

		if (service.isNewData()) {
			repository.addService(service);
		}
		
		service.setNewData(false);
	}
	
	public void store(String name, WDCTemplate template) throws Exception {
		
		if (template.isNewData()) {
			template.setId(null);
		}
		
		daos.get(name).store(template);

		if (template.isNewData()) {
			repository.addTemplate(template);
		}
		
		template.setNewData(false);
	}

	
}
